package com.wow.app.promotion.web.open.common;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.citrus.service.pipeline.PipelineContext;
import com.alibaba.citrus.service.pipeline.support.AbstractValve;
import com.alibaba.citrus.service.uribroker.URIBrokerService;
import com.alibaba.citrus.turbine.TurbineRunData;
import com.alibaba.citrus.turbine.uribroker.uri.TurbineURIBroker;
import com.alibaba.citrus.turbine.util.TurbineUtil;
import com.alibaba.citrus.util.ServletUtil;
import com.alibaba.citrus.util.StringUtil;
import com.wow.app.biz.common.SessionUser;
import com.wow.app.biz.common.SessionUtil;

public class UserLoginValve extends AbstractValve {
	@Resource
	URIBrokerService uriBrokerService;
	@Resource
	HttpServletRequest httpRequest;
	@Resource
	private List whiteList;

	@Override
	public void invoke(PipelineContext pipelineContext) throws Exception {
		String path = ServletUtil.getResourcePath(httpRequest);

		if (isNeedLogin(path)) {
			HttpSession session = httpRequest.getSession();
			SessionUser sessionUser = SessionUtil.getSessionUser(session);
			TurbineRunData rundata = TurbineUtil.getTurbineRunData(httpRequest);
			if (sessionUser == null || sessionUser.getLoginID() == null) {
				TurbineURIBroker uriBroker = (TurbineURIBroker) uriBrokerService
						.getURIBroker("openModule");
				String returnUrl = httpRequest.getRequestURL().toString();
				if (httpRequest.getQueryString() != null) {
					returnUrl = returnUrl + "?" + httpRequest.getQueryString();
				}
				rundata.setRedirectLocation(uriBroker.setTarget("login.vm")
						.addQueryData("returnUrl", returnUrl).render());
			}
		}
		pipelineContext.invokeNext();
	}

	private boolean isNeedLogin(String path) {
		String s1 = StringUtil.split(path, ".")[0] + ".vm";
		return whiteList != null && whiteList.contains(s1) ? false : true;
	}
}
